package com.xingkeduo.pojo.json;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xingkeduo.pojo.table.PostsTable;
import com.xingkeduo.util.pojo.base.BaseJson;
import com.xingkeduo.util.pojo.domain.Page;
import com.xingkeduo.util.pojo.enums.YesNoEnum;
import com.xingkeduo.util.pojo.exception.InputParamException;
import com.xingkeduo.util.tool.CommonUtil;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;

public class PostsJson extends BaseJson {

	public static long createQueryForPosts(String json) throws Throwable {
		JsonNode root = validJson(json);
		if (root == null){
			throw new InputParamException(InputParamException.Type.INVALID, "参数格式");
		}
		return validId(root, YesNoEnum.YES);
	}

	public static PostsTable createTableForModifyPosts(String urlParam, PostsTable postsTable) throws Throwable {
		JsonNode root = validJson(urlParam);
		if (root == null)
			throw new InputParamException(InputParamException.Type.INVALID, "参数");
		postsTable.setId(validId(root, YesNoEnum.YES));

		return postsTable;
	}


	public static ObjectNode toJson(PostsTable postsTable) {
		ObjectNode root = MAPPER.createObjectNode();

		if (postsTable != null)
		{
			root.put("id", postsTable.getId());
			root.put("code", postsTable.getCode());
			root.put("name", postsTable.getName());
            root.put("enname", postsTable.getEnname());
            root.put("deptId", postsTable.getDeptId());
            root.put("deptName", postsTable.getDeptName());
			root.put("intro", postsTable.getIntro());
			root.put("sort", postsTable.getSort());
			root.put("status", postsTable.getStatus());
			//处理时间
			String createdTime =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(postsTable.getCreatedTime());
			root.put("createtime", createdTime);
		}
		return root;
	}

	public static ArrayNode toJson(List<PostsTable> postsTableList) throws Throwable {
		ArrayNode root = MAPPER.createArrayNode();

		if(!CommonUtil.isEmpty(postsTableList)){
			for (Iterator<PostsTable> iterator = postsTableList.iterator(); iterator.hasNext();) {
				root.add(toJson(iterator.next()));
			}
		}

		return root;
	}
	public static ObjectNode toJsonPage(Page<PostsTable> page) throws Throwable {
		ObjectNode root = MAPPER.createObjectNode();
		if (page != null)
		{
			root.put("pageNo", page.getPageNo());
			root.put("pageSize", page.getPageSize());
			root.put("pageTotal", page.getPageTotal());
			root.put("recordTotal", page.getRecordTotal());
			root.put("dtoLists", toJson(page.getDtoList()));
		}
		return root;
	}

}
